home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-installer.exe / bin / ftplib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  33KB  |  1,135 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. """An FTP client class and some helper functions.
  5.  
  6. Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
  7.  
  8. Example:
  9.  
  10. >>> from ftplib import FTP
  11. >>> ftp = FTP('ftp.python.org') # connect to host, default port
  12. >>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
  13. '230 Guest login ok, access restrictions apply.'
  14. >>> ftp.retrlines('LIST') # list directory contents
  15. total 9
  16. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
  17. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
  18. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
  19. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
  20. d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
  21. drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
  22. drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
  23. drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
  24. -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
  25. '226 Transfer complete.'
  26. >>> ftp.quit()
  27. '221 Goodbye.'
  28. >>>
  29.  
  30. A nice test that reveals some of the network dialogue would be:
  31. python ftplib.py -d localhost -l -p -l
  32. """
  33. import os
  34. import sys
  35.  
  36. try:
  37.     import SOCKS
  38.     socket = SOCKS
  39.     del SOCKS
  40.     from socket import getfqdn
  41.     socket.getfqdn = getfqdn
  42.     del getfqdn
  43. except ImportError:
  44.     import socket
  45.  
  46. from socket import _GLOBAL_DEFAULT_TIMEOUT
  47. __all__ = [
  48.     'FTP',
  49.     'Netrc']
  50. MSG_OOB = 1
  51. FTP_PORT = 21
  52. MAXLINE = 8192
  53.  
  54. class Error(Exception):
  55.     pass
  56.  
  57.  
  58. class error_reply(Error):
  59.     pass
  60.  
  61.  
  62. class error_temp(Error):
  63.     pass
  64.  
  65.  
  66. class error_perm(Error):
  67.     pass
  68.  
  69.  
  70. class error_proto(Error):
  71.     pass
  72.  
  73. all_errors = (Error, IOError, EOFError)
  74. CRLF = '\r\n'
  75.  
  76. class FTP:
  77.     """An FTP client class.
  78.  
  79.     To create a connection, call the class using these arguments:
  80.             host, user, passwd, acct, timeout
  81.  
  82.     The first four arguments are all strings, and have default value ''.
  83.     timeout must be numeric and defaults to None if not passed,
  84.     meaning that no timeout will be set on any ftp socket(s)
  85.     If a timeout is passed, then this is now the default timeout for all ftp
  86.     socket operations for this instance.
  87.  
  88.     Then use self.connect() with optional host and port argument.
  89.  
  90.     To download a file, use ftp.retrlines('RETR ' + filename),
  91.     or ftp.retrbinary() with slightly different arguments.
  92.     To upload a file, use ftp.storlines() or ftp.storbinary(),
  93.     which have an open file as argument (see their definitions
  94.     below for details).
  95.     The download/upload functions first issue appropriate TYPE
  96.     and PORT or PASV commands.
  97. """
  98.     debugging = 0
  99.     host = ''
  100.     port = FTP_PORT
  101.     maxline = MAXLINE
  102.     sock = None
  103.     file = None
  104.     welcome = None
  105.     passiveserver = 1
  106.     
  107.     def __init__(self, host = '', user = '', passwd = '', acct = '', timeout = _GLOBAL_DEFAULT_TIMEOUT):
  108.         self.timeout = timeout
  109.         if host:
  110.             self.connect(host)
  111.             if user:
  112.                 self.login(user, passwd, acct)
  113.             
  114.  
  115.     
  116.     def connect(self, host = '', port = 0, timeout = -999):
  117.         '''Connect to host.  Arguments are:
  118.          - host: hostname to connect to (string, default previous host)
  119.          - port: port to connect to (integer, default previous port)
  120.         '''
  121.         if host != '':
  122.             self.host = host
  123.         if port > 0:
  124.             self.port = port
  125.         if timeout != -999:
  126.             self.timeout = timeout
  127.         self.sock = socket.create_connection((self.host, self.port), self.timeout)
  128.         self.af = self.sock.family
  129.         self.file = self.sock.makefile('rb')
  130.         self.welcome = self.getresp()
  131.         return self.welcome
  132.  
  133.     
  134.     def getwelcome(self):
  135.         '''Get the welcome message from the server.
  136.         (this is read and squirreled away by connect())'''
  137.         if self.debugging:
  138.             print '*welcome*', self.sanitize(self.welcome)
  139.         return self.welcome
  140.  
  141.     
  142.     def set_debuglevel(self, level):
  143.         '''Set the debugging level.
  144.         The required argument level means:
  145.         0: no debugging output (default)
  146.         1: print commands and responses but not body text etc.
  147.         2: also print raw lines read and sent before stripping CR/LF'''
  148.         self.debugging = level
  149.  
  150.     debug = set_debuglevel
  151.     
  152.     def set_pasv(self, val):
  153.         '''Use passive or active mode for data transfers.
  154.         With a false argument, use the normal PORT mode,
  155.         With a true argument, use the PASV command.'''
  156.         self.passiveserver = val
  157.  
  158.     
  159.     def sanitize(self, s):
  160.         if s[:5] == 'pass ' or s[:5] == 'PASS ':
  161.             i = len(s)
  162.             while i > 5 and s[i - 1] in '\r\n':
  163.                 i = i - 1
  164.             s = s[:5] + '*' * (i - 5) + s[i:]
  165.         return repr(s)
  166.  
  167.     
  168.     def putline(self, line):
  169.         line = line + CRLF
  170.         if self.debugging > 1:
  171.             print '*put*', self.sanitize(line)
  172.         self.sock.sendall(line)
  173.  
  174.     
  175.     def putcmd(self, line):
  176.         if self.debugging:
  177.             print '*cmd*', self.sanitize(line)
  178.         self.putline(line)
  179.  
  180.     
  181.     def getline(self):
  182.         line = self.file.readline(self.maxline + 1)
  183.         if len(line) > self.maxline:
  184.             raise Error('got more than %d bytes' % self.maxline)
  185.         if self.debugging > 1:
  186.             print '*get*', self.sanitize(line)
  187.         if not line:
  188.             raise EOFError
  189.         if line[-2:] == CRLF:
  190.             line = line[:-2]
  191.         elif line[-1:] in CRLF:
  192.             line = line[:-1]
  193.         return line
  194.  
  195.     
  196.     def getmultiline(self):
  197.         line = self.getline()
  198.         if line[3:4] == '-':
  199.             code = line[:3]
  200.             while None:
  201.                 nextline = self.getline()
  202.                 line = line + '\n' + nextline
  203.                 if nextline[:3] == code and nextline[3:4] != '-':
  204.                     break
  205.                     continue
  206.                     continue
  207.                 return line
  208.  
  209.     
  210.     def getresp(self):
  211.         resp = self.getmultiline()
  212.         if self.debugging:
  213.             print '*resp*', self.sanitize(resp)
  214.         self.lastresp = resp[:3]
  215.         c = resp[:1]
  216.         if c in ('1', '2', '3'):
  217.             return resp
  218.         if None == '4':
  219.             raise error_temp, resp
  220.         if c == '5':
  221.             raise error_perm, resp
  222.         raise error_proto, resp
  223.  
  224.     
  225.     def voidresp(self):
  226.         """Expect a response beginning with '2'."""
  227.         resp = self.getresp()
  228.         if resp[:1] != '2':
  229.             raise error_reply, resp
  230.         return resp
  231.  
  232.     
  233.     def abort(self):
  234.         """Abort a file transfer.  Uses out-of-band data.
  235.         This does not follow the procedure from the RFC to send Telnet
  236.         IP and Synch; that doesn't seem to work with the servers I've
  237.         tried.  Instead, just send the ABOR command as OOB data."""
  238.         line = 'ABOR' + CRLF
  239.         if self.debugging > 1:
  240.             print '*put urgent*', self.sanitize(line)
  241.         self.sock.sendall(line, MSG_OOB)
  242.         resp = self.getmultiline()
  243.         if resp[:3] not in ('426', '225', '226'):
  244.             raise error_proto, resp
  245.  
  246.     
  247.     def sendcmd(self, cmd):
  248.         '''Send a command and return the response.'''
  249.         self.putcmd(cmd)
  250.         return self.getresp()
  251.  
  252.     
  253.     def voidcmd(self, cmd):
  254.         """Send a command and expect a response beginning with '2'."""
  255.         self.putcmd(cmd)
  256.         return self.voidresp()
  257.  
  258.     
  259.     def sendport(self, host, port):
  260.         '''Send a PORT command with the current host and the given
  261.         port number.
  262.         '''
  263.         hbytes = host.split('.')
  264.         pbytes = [
  265.             repr(port // 256),
  266.             repr(port % 256)]
  267.         bytes = hbytes + pbytes
  268.         cmd = 'PORT ' + ','.join(bytes)
  269.         return self.voidcmd(cmd)
  270.  
  271.     
  272.     def sendeprt(self, host, port):
  273.         '''Send a EPRT command with the current host and the given port number.'''
  274.         af = 0
  275.         if self.af == socket.AF_INET:
  276.             af = 1
  277.         if self.af == socket.AF_INET6:
  278.             af = 2
  279.         if af == 0:
  280.             raise error_proto, 'unsupported address family'
  281.         fields = [
  282.             '',
  283.             repr(af),
  284.             host,
  285.             repr(port),
  286.             '']
  287.         cmd = 'EPRT ' + '|'.join(fields)
  288.         return self.voidcmd(cmd)
  289.  
  290.     
  291.     def makeport(self):
  292.         '''Create a new socket and send a PORT command for it.'''
  293.         err = None
  294.         sock = None
  295.         for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
  296.             (af, socktype, proto, canonname, sa) = res
  297.             
  298.             try:
  299.                 sock = socket.socket(af, socktype, proto)
  300.                 sock.bind(sa)
  301.             except socket.error:
  302.                 err = None
  303.                 if sock:
  304.                     sock.close()
  305.                 sock = None
  306.                 continue
  307.  
  308.             break
  309.         
  310.         if sock is None:
  311.             if err is not None:
  312.                 raise err
  313.             raise socket.error('getaddrinfo returns an empty list')
  314.         sock.listen(1)
  315.         port = sock.getsockname()[1]
  316.         host = self.sock.getsockname()[0]
  317.         if self.af == socket.AF_INET:
  318.             resp = self.sendport(host, port)
  319.         else:
  320.             resp = self.sendeprt(host, port)
  321.         if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  322.             sock.settimeout(self.timeout)
  323.         return sock
  324.  
  325.     
  326.     def makepasv(self):
  327.         if self.af == socket.AF_INET:
  328.             (host, port) = parse227(self.sendcmd('PASV'))
  329.         else:
  330.             (host, port) = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
  331.         return (host, port)
  332.  
  333.     
  334.     def ntransfercmd(self, cmd, rest = None):
  335.         """Initiate a transfer over the data connection.
  336.  
  337.         If the transfer is active, send a port command and the
  338.         transfer command, and accept the connection.  If the server is
  339.         passive, send a pasv command, connect to it, and start the
  340.         transfer command.  Either way, return the socket for the
  341.         connection and the expected size of the transfer.  The
  342.         expected size may be None if it could not be determined.
  343.  
  344.         Optional `rest' argument can be a string that is sent as the
  345.         argument to a REST command.  This is essentially a server
  346.         marker used to tell the server to skip over any data up to the
  347.         given marker.
  348.         """
  349.         size = None
  350.         if self.passiveserver:
  351.             (host, port) = self.makepasv()
  352.             conn = socket.create_connection((host, port), self.timeout)
  353.             
  354.             try:
  355.                 if rest is not None:
  356.                     self.sendcmd('REST %s' % rest)
  357.                 resp = self.sendcmd(cmd)
  358.                 if resp[0] == '2':
  359.                     resp = self.getresp()
  360.                 if resp[0] != '1':
  361.                     raise error_reply, resp
  362.             conn.close()
  363.             raise 
  364.  
  365.         else:
  366.             sock = self.makeport()
  367.             
  368.             try:
  369.                 if rest is not None:
  370.                     self.sendcmd('REST %s' % rest)
  371.                 resp = self.sendcmd(cmd)
  372.                 if resp[0] == '2':
  373.                     resp = self.getresp()
  374.                 if resp[0] != '1':
  375.                     raise error_reply, resp
  376.                 (conn, sockaddr) = sock.accept()
  377.                 if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  378.                     conn.settimeout(self.timeout)
  379.             finally:
  380.                 sock.close()
  381.  
  382.         if resp[:3] == '150':
  383.             size = parse150(resp)
  384.         return (conn, size)
  385.  
  386.     
  387.     def transfercmd(self, cmd, rest = None):
  388.         '''Like ntransfercmd() but returns only the socket.'''
  389.         return self.ntransfercmd(cmd, rest)[0]
  390.  
  391.     
  392.     def login(self, user = '', passwd = '', acct = ''):
  393.         '''Login, default anonymous.'''
  394.         if not user:
  395.             user = 'anonymous'
  396.         if not passwd:
  397.             passwd = ''
  398.         if not acct:
  399.             acct = ''
  400.         if user == 'anonymous' and passwd in ('', '-'):
  401.             passwd = passwd + 'anonymous@'
  402.         resp = self.sendcmd('USER ' + user)
  403.         if resp[0] == '3':
  404.             resp = self.sendcmd('PASS ' + passwd)
  405.         if resp[0] == '3':
  406.             resp = self.sendcmd('ACCT ' + acct)
  407.         if resp[0] != '2':
  408.             raise error_reply, resp
  409.         return resp
  410.  
  411.     
  412.     def retrbinary(self, cmd, callback, blocksize = 8192, rest = None):
  413.         '''Retrieve data in binary mode.  A new port is created for you.
  414.  
  415.         Args:
  416.           cmd: A RETR command.
  417.           callback: A single parameter callable to be called on each
  418.                     block of data read.
  419.           blocksize: The maximum number of bytes to read from the
  420.                      socket at one time.  [default: 8192]
  421.           rest: Passed to transfercmd().  [default: None]
  422.  
  423.         Returns:
  424.           The response code.
  425.         '''
  426.         self.voidcmd('TYPE I')
  427.         conn = self.transfercmd(cmd, rest)
  428.         while None:
  429.             data = conn.recv(blocksize)
  430.             if not data:
  431.                 break
  432.             continue
  433.             conn.close()
  434.             return self.voidresp()
  435.  
  436.     
  437.     def retrlines(self, cmd, callback = None):
  438.         '''Retrieve data in line mode.  A new port is created for you.
  439.  
  440.         Args:
  441.           cmd: A RETR, LIST, NLST, or MLSD command.
  442.           callback: An optional single parameter callable that is called
  443.                     for each line with the trailing CRLF stripped.
  444.                     [default: print_line()]
  445.  
  446.         Returns:
  447.           The response code.
  448.         '''
  449.         if callback is None:
  450.             callback = print_line
  451.         resp = self.sendcmd('TYPE A')
  452.         conn = self.transfercmd(cmd)
  453.         fp = conn.makefile('rb')
  454.         while None:
  455.             line = fp.readline(self.maxline + 1)
  456.             if len(line) > self.maxline:
  457.                 raise Error('got more than %d bytes' % self.maxline)
  458.             if self.debugging > 2:
  459.                 print '*retr*', repr(line)
  460.             if not line:
  461.                 break
  462.             if line[-2:] == CRLF:
  463.                 line = line[:-2]
  464.             elif line[-1:] == '\n':
  465.                 line = line[:-1]
  466.             continue
  467.             fp.close()
  468.             conn.close()
  469.             return self.voidresp()
  470.  
  471.     
  472.     def storbinary(self, cmd, fp, blocksize = 8192, callback = None, rest = None):
  473.         '''Store a file in binary mode.  A new port is created for you.
  474.  
  475.         Args:
  476.           cmd: A STOR command.
  477.           fp: A file-like object with a read(num_bytes) method.
  478.           blocksize: The maximum data size to read from fp and send over
  479.                      the connection at once.  [default: 8192]
  480.           callback: An optional single parameter callable that is called on
  481.                     each block of data after it is sent.  [default: None]
  482.           rest: Passed to transfercmd().  [default: None]
  483.  
  484.         Returns:
  485.           The response code.
  486.         '''
  487.         self.voidcmd('TYPE I')
  488.         conn = self.transfercmd(cmd, rest)
  489.         while None:
  490.             buf = fp.read(blocksize)
  491.             if not buf:
  492.                 break
  493.             if callback:
  494.                 callback(buf)
  495.                 continue
  496.                 continue
  497.                 conn.close()
  498.                 return self.voidresp()
  499.  
  500.     
  501.     def storlines(self, cmd, fp, callback = None):
  502.         '''Store a file in line mode.  A new port is created for you.
  503.  
  504.         Args:
  505.           cmd: A STOR command.
  506.           fp: A file-like object with a readline() method.
  507.           callback: An optional single parameter callable that is called on
  508.                     each line after it is sent.  [default: None]
  509.  
  510.         Returns:
  511.           The response code.
  512.         '''
  513.         self.voidcmd('TYPE A')
  514.         conn = self.transfercmd(cmd)
  515.         while None:
  516.             buf = fp.readline(self.maxline + 1)
  517.             if len(buf) > self.maxline:
  518.                 raise Error('got more than %d bytes' % self.maxline)
  519.             if not buf:
  520.                 break
  521.             if buf[-2:] != CRLF:
  522.                 if buf[-1] in CRLF:
  523.                     buf = buf[:-1]
  524.                 buf = buf + CRLF
  525.             if callback:
  526.                 callback(buf)
  527.                 continue
  528.                 continue
  529.                 conn.close()
  530.                 return self.voidresp()
  531.  
  532.     
  533.     def acct(self, password):
  534.         '''Send new account name.'''
  535.         cmd = 'ACCT ' + password
  536.         return self.voidcmd(cmd)
  537.  
  538.     
  539.     def nlst(self, *args):
  540.         '''Return a list of files in a given directory (default the current).'''
  541.         cmd = 'NLST'
  542.         for arg in args:
  543.             cmd = cmd + ' ' + arg
  544.         
  545.         files = []
  546.         self.retrlines(cmd, files.append)
  547.         return files
  548.  
  549.     
  550.     def dir(self, *args):
  551.         '''List a directory in long form.
  552.         By default list current directory to stdout.
  553.         Optional last argument is callback function; all
  554.         non-empty arguments before it are concatenated to the
  555.         LIST command.  (This *should* only be used for a pathname.)'''
  556.         cmd = 'LIST'
  557.         func = None
  558.         if args[-1:] and type(args[-1]) != type(''):
  559.             args = args[:-1]
  560.             func = args[-1]
  561.         for arg in args:
  562.             if arg:
  563.                 cmd = cmd + ' ' + arg
  564.                 continue
  565.         self.retrlines(cmd, func)
  566.  
  567.     
  568.     def rename(self, fromname, toname):
  569.         '''Rename a file.'''
  570.         resp = self.sendcmd('RNFR ' + fromname)
  571.         if resp[0] != '3':
  572.             raise error_reply, resp
  573.         return self.voidcmd('RNTO ' + toname)
  574.  
  575.     
  576.     def delete(self, filename):
  577.         '''Delete a file.'''
  578.         resp = self.sendcmd('DELE ' + filename)
  579.         if resp[:3] in ('250', '200'):
  580.             return resp
  581.         raise None, resp
  582.  
  583.     
  584.     def cwd(self, dirname):
  585.         '''Change to a directory.'''
  586.         if dirname == '..':
  587.             
  588.             try:
  589.                 return self.voidcmd('CDUP')
  590.             except error_perm:
  591.                 msg = None
  592.                 if msg.args[0][:3] != '500':
  593.                     raise 
  594.             
  595.  
  596.         if dirname == '':
  597.             dirname = '.'
  598.         cmd = 'CWD ' + dirname
  599.         return self.voidcmd(cmd)
  600.  
  601.     
  602.     def size(self, filename):
  603.         '''Retrieve the size of a file.'''
  604.         resp = self.sendcmd('SIZE ' + filename)
  605.         if resp[:3] == '213':
  606.             s = resp[3:].strip()
  607.             
  608.             try:
  609.                 return int(s)
  610.             except (OverflowError, ValueError):
  611.                 return long(s)
  612.             
  613.  
  614.  
  615.     
  616.     def mkd(self, dirname):
  617.         '''Make a directory, return its full pathname.'''
  618.         resp = self.sendcmd('MKD ' + dirname)
  619.         return parse257(resp)
  620.  
  621.     
  622.     def rmd(self, dirname):
  623.         '''Remove a directory.'''
  624.         return self.voidcmd('RMD ' + dirname)
  625.  
  626.     
  627.     def pwd(self):
  628.         '''Return current working directory.'''
  629.         resp = self.sendcmd('PWD')
  630.         return parse257(resp)
  631.  
  632.     
  633.     def quit(self):
  634.         '''Quit, and close the connection.'''
  635.         resp = self.voidcmd('QUIT')
  636.         self.close()
  637.         return resp
  638.  
  639.     
  640.     def close(self):
  641.         '''Close the connection without assuming anything about it.'''
  642.         if self.file is not None:
  643.             self.file.close()
  644.         if self.sock is not None:
  645.             self.sock.close()
  646.         self.file = None
  647.         self.sock = None
  648.  
  649.  
  650.  
  651. try:
  652.     import ssl
  653. except ImportError:
  654.     pass
  655.  
  656.  
  657. class FTP_TLS(FTP):
  658.     """A FTP subclass which adds TLS support to FTP as described
  659.         in RFC-4217.
  660.  
  661.         Connect as usual to port 21 implicitly securing the FTP control
  662.         connection before authenticating.
  663.  
  664.         Securing the data connection requires user to explicitly ask
  665.         for it by calling prot_p() method.
  666.  
  667.         Usage example:
  668.         >>> from ftplib import FTP_TLS
  669.         >>> ftps = FTP_TLS('ftp.python.org')
  670.         >>> ftps.login()  # login anonymously previously securing control channel
  671.         '230 Guest login ok, access restrictions apply.'
  672.         >>> ftps.prot_p()  # switch to secure data connection
  673.         '200 Protection level set to P'
  674.         >>> ftps.retrlines('LIST')  # list directory content securely
  675.         total 9
  676.         drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
  677.         drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
  678.         drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
  679.         drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
  680.         d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
  681.         drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
  682.         drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
  683.         drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
  684.         -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
  685.         '226 Transfer complete.'
  686.         >>> ftps.quit()
  687.         '221 Goodbye.'
  688.         >>>
  689.         """
  690.     ssl_version = ssl.PROTOCOL_TLSv1
  691.     
  692.     def __init__(self, host = '', user = '', passwd = '', acct = '', keyfile = None, certfile = None, timeout = _GLOBAL_DEFAULT_TIMEOUT):
  693.         self.keyfile = keyfile
  694.         self.certfile = certfile
  695.         self._prot_p = False
  696.         FTP.__init__(self, host, user, passwd, acct, timeout)
  697.  
  698.     
  699.     def login(self, user = '', passwd = '', acct = '', secure = True):
  700.         if secure and not isinstance(self.sock, ssl.SSLSocket):
  701.             self.auth()
  702.         return FTP.login(self, user, passwd, acct)
  703.  
  704.     
  705.     def auth(self):
  706.         '''Set up secure control connection by using TLS/SSL.'''
  707.         if isinstance(self.sock, ssl.SSLSocket):
  708.             raise ValueError('Already using TLS')
  709.         if self.ssl_version == ssl.PROTOCOL_TLSv1:
  710.             resp = self.voidcmd('AUTH TLS')
  711.         else:
  712.             resp = self.voidcmd('AUTH SSL')
  713.         self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ssl_version = self.ssl_version)
  714.         self.file = self.sock.makefile(mode = 'rb')
  715.         return resp
  716.  
  717.     
  718.     def prot_p(self):
  719.         '''Set up secure data connection.'''
  720.         self.voidcmd('PBSZ 0')
  721.         resp = self.voidcmd('PROT P')
  722.         self._prot_p = True
  723.         return resp
  724.  
  725.     
  726.     def prot_c(self):
  727.         '''Set up clear text data connection.'''
  728.         resp = self.voidcmd('PROT C')
  729.         self._prot_p = False
  730.         return resp
  731.  
  732.     
  733.     def ntransfercmd(self, cmd, rest = None):
  734.         (conn, size) = FTP.ntransfercmd(self, cmd, rest)
  735.         if self._prot_p:
  736.             conn = ssl.wrap_socket(conn, self.keyfile, self.certfile, ssl_version = self.ssl_version)
  737.         return (conn, size)
  738.  
  739.     
  740.     def retrbinary(self, cmd, callback, blocksize = 8192, rest = None):
  741.         self.voidcmd('TYPE I')
  742.         conn = self.transfercmd(cmd, rest)
  743.         
  744.         try:
  745.             while None:
  746.                 data = conn.recv(blocksize)
  747.                 if not data:
  748.                     break
  749.                 continue
  750.                 if isinstance(conn, ssl.SSLSocket):
  751.                     conn.unwrap()
  752.             conn.close()
  753.             return self.voidresp()
  754.  
  755.  
  756.     
  757.     def retrlines(self, cmd, callback = None):
  758.         if callback is None:
  759.             callback = print_line
  760.         resp = self.sendcmd('TYPE A')
  761.         conn = self.transfercmd(cmd)
  762.         fp = conn.makefile('rb')
  763.         
  764.         try:
  765.             while None:
  766.                 line = fp.readline(self.maxline + 1)
  767.                 if len(line) > self.maxline:
  768.                     raise Error('got more than %d bytes' % self.maxline)
  769.                 if self.debugging > 2:
  770.                     print '*retr*', repr(line)
  771.                 if not line:
  772.                     break
  773.                 if line[-2:] == CRLF:
  774.                     line = line[:-2]
  775.                 elif line[-1:] == '\n':
  776.                     line = line[:-1]
  777.                 continue
  778.                 if isinstance(conn, ssl.SSLSocket):
  779.                     conn.unwrap()
  780.             fp.close()
  781.             conn.close()
  782.             return self.voidresp()
  783.  
  784.  
  785.     
  786.     def storbinary(self, cmd, fp, blocksize = 8192, callback = None, rest = None):
  787.         self.voidcmd('TYPE I')
  788.         conn = self.transfercmd(cmd, rest)
  789.         
  790.         try:
  791.             while None:
  792.                 buf = fp.read(blocksize)
  793.                 if not buf:
  794.                     break
  795.                 if callback:
  796.                     callback(buf)
  797.                     continue
  798.                     continue
  799.                     if isinstance(conn, ssl.SSLSocket):
  800.                         conn.unwrap()
  801.                 conn.close()
  802.                 return self.voidresp()
  803.  
  804.  
  805.     
  806.     def storlines(self, cmd, fp, callback = None):
  807.         self.voidcmd('TYPE A')
  808.         conn = self.transfercmd(cmd)
  809.         
  810.         try:
  811.             while None:
  812.                 buf = fp.readline(self.maxline + 1)
  813.                 if len(buf) > self.maxline:
  814.                     raise Error('got more than %d bytes' % self.maxline)
  815.                 if not buf:
  816.                     break
  817.                 if buf[-2:] != CRLF:
  818.                     if buf[-1] in CRLF:
  819.                         buf = buf[:-1]
  820.                     buf = buf + CRLF
  821.                 if callback:
  822.                     callback(buf)
  823.                     continue
  824.                     continue
  825.                     if isinstance(conn, ssl.SSLSocket):
  826.                         conn.unwrap()
  827.                 conn.close()
  828.                 return self.voidresp()
  829.  
  830.  
  831.  
  832. __all__.append('FTP_TLS')
  833. all_errors = (Error, IOError, EOFError, ssl.SSLError)
  834. _150_re = None
  835.  
  836. def parse150(resp):
  837.     """Parse the '150' response for a RETR request.
  838.     Returns the expected transfer size or None; size is not guaranteed to
  839.     be present in the 150 message.
  840.     """
  841.     global _150_re
  842.     if resp[:3] != '150':
  843.         raise error_reply, resp
  844.     if _150_re is None:
  845.         import re as re
  846.         _150_re = re.compile('150 .* \\((\\d+) bytes\\)', re.IGNORECASE)
  847.     m = _150_re.match(resp)
  848.     if not m:
  849.         return None
  850.     s = None.group(1)
  851.     
  852.     try:
  853.         return int(s)
  854.     except (OverflowError, ValueError):
  855.         return long(s)
  856.  
  857.  
  858. _227_re = None
  859.  
  860. def parse227(resp):
  861.     """Parse the '227' response for a PASV request.
  862.     Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
  863.     Return ('host.addr.as.numbers', port#) tuple."""
  864.     global _227_re
  865.     if resp[:3] != '227':
  866.         raise error_reply, resp
  867.     if _227_re is None:
  868.         import re
  869.         _227_re = re.compile('(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+)')
  870.     m = _227_re.search(resp)
  871.     if not m:
  872.         raise error_proto, resp
  873.     numbers = m.groups()
  874.     host = '.'.join(numbers[:4])
  875.     port = (int(numbers[4]) << 8) + int(numbers[5])
  876.     return (host, port)
  877.  
  878.  
  879. def parse229(resp, peer):
  880.     """Parse the '229' response for a EPSV request.
  881.     Raises error_proto if it does not contain '(|||port|)'
  882.     Return ('host.addr.as.numbers', port#) tuple."""
  883.     if resp[:3] != '229':
  884.         raise error_reply, resp
  885.     left = resp.find('(')
  886.     if left < 0:
  887.         raise error_proto, resp
  888.     right = resp.find(')', left + 1)
  889.     if right < 0:
  890.         raise error_proto, resp
  891.     if resp[left + 1] != resp[right - 1]:
  892.         raise error_proto, resp
  893.     parts = resp[left + 1:right].split(resp[left + 1])
  894.     if len(parts) != 5:
  895.         raise error_proto, resp
  896.     host = peer[0]
  897.     port = int(parts[3])
  898.     return (host, port)
  899.  
  900.  
  901. def parse257(resp):
  902.     """Parse the '257' response for a MKD or PWD request.
  903.     This is a response to a MKD or PWD request: a directory name.
  904.     Returns the directoryname in the 257 reply."""
  905.     if resp[:3] != '257':
  906.         raise error_reply, resp
  907.     if resp[3:5] != ' "':
  908.         return ''
  909.     dirname = None
  910.     i = 5
  911.     n = len(resp)
  912.     while i < n:
  913.         c = resp[i]
  914.         i = i + 1
  915.         if c == '"':
  916.             if i >= n or resp[i] != '"':
  917.                 break
  918.             i = i + 1
  919.         dirname = dirname + c
  920.     return dirname
  921.  
  922.  
  923. def print_line(line):
  924.     '''Default retrlines callback to print a line.'''
  925.     print line
  926.  
  927.  
  928. def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
  929.     '''Copy file from one FTP-instance to another.'''
  930.     if not targetname:
  931.         targetname = sourcename
  932.     type = 'TYPE ' + type
  933.     source.voidcmd(type)
  934.     target.voidcmd(type)
  935.     (sourcehost, sourceport) = parse227(source.sendcmd('PASV'))
  936.     target.sendport(sourcehost, sourceport)
  937.     treply = target.sendcmd('STOR ' + targetname)
  938.     if treply[:3] not in ('125', '150'):
  939.         raise error_proto
  940.     sreply = source.sendcmd('RETR ' + sourcename)
  941.     if sreply[:3] not in ('125', '150'):
  942.         raise error_proto
  943.     source.voidresp()
  944.     target.voidresp()
  945.  
  946.  
  947. class Netrc:
  948.     """Class to parse & provide access to 'netrc' format files.
  949.  
  950.     See the netrc(4) man page for information on the file format.
  951.  
  952.     WARNING: This class is obsolete -- use module netrc instead.
  953.  
  954.     """
  955.     __defuser = None
  956.     __defpasswd = None
  957.     __defacct = None
  958.     
  959.     def __init__(self, filename = None):
  960.         if filename is None:
  961.             if 'HOME' in os.environ:
  962.                 filename = os.path.join(os.environ['HOME'], '.netrc')
  963.             else:
  964.                 raise IOError, 'specify file to load or set $HOME'
  965.         self._Netrc__hosts = { }
  966.         self._Netrc__macros = { }
  967.         fp = open(filename, 'r')
  968.         in_macro = 0
  969.         while None:
  970.             line = fp.readline(self.maxline + 1)
  971.             if len(line) > self.maxline:
  972.                 raise Error('got more than %d bytes' % self.maxline)
  973.             if not line:
  974.                 break
  975.             if in_macro and line.strip():
  976.                 macro_lines.append(line)
  977.                 continue
  978.             elif in_macro:
  979.                 self._Netrc__macros[macro_name] = tuple(macro_lines)
  980.                 in_macro = 0
  981.             words = line.split()
  982.             host = None
  983.             user = None
  984.             passwd = None
  985.             acct = None
  986.             default = 0
  987.             i = 0
  988.             while i < len(words):
  989.                 w1 = words[i]
  990.                 if i + 1 < len(words):
  991.                     w2 = words[i + 1]
  992.                 else:
  993.                     w2 = None
  994.                 if w1 == 'default':
  995.                     default = 1
  996.                 elif w1 == 'machine' and w2:
  997.                     host = w2.lower()
  998.                     i = i + 1
  999.                 elif w1 == 'login' and w2:
  1000.                     user = w2
  1001.                     i = i + 1
  1002.                 elif w1 == 'password' and w2:
  1003.                     passwd = w2
  1004.                     i = i + 1
  1005.                 elif w1 == 'account' and w2:
  1006.                     acct = w2
  1007.                     i = i + 1
  1008.                 elif w1 == 'macdef' and w2:
  1009.                     macro_name = w2
  1010.                     macro_lines = []
  1011.                     in_macro = 1
  1012.                     break
  1013.                 i = i + 1
  1014.             if default:
  1015.                 if not user:
  1016.                     pass
  1017.                 self._Netrc__defuser = self._Netrc__defuser
  1018.                 if not passwd:
  1019.                     pass
  1020.                 self._Netrc__defpasswd = self._Netrc__defpasswd
  1021.                 if not acct:
  1022.                     pass
  1023.                 self._Netrc__defacct = self._Netrc__defacct
  1024.             if host or host in self._Netrc__hosts:
  1025.                 (ouser, opasswd, oacct) = self._Netrc__hosts[host]
  1026.                 if not user:
  1027.                     pass
  1028.                 user = ouser
  1029.                 if not passwd:
  1030.                     pass
  1031.                 passwd = opasswd
  1032.                 if not acct:
  1033.                     pass
  1034.                 acct = oacct
  1035.             self._Netrc__hosts[host] = (user, passwd, acct)
  1036.             continue
  1037.             continue
  1038.             return None
  1039.  
  1040.     
  1041.     def get_hosts(self):
  1042.         '''Return a list of hosts mentioned in the .netrc file.'''
  1043.         return self._Netrc__hosts.keys()
  1044.  
  1045.     
  1046.     def get_account(self, host):
  1047.         '''Returns login information for the named host.
  1048.  
  1049.         The return value is a triple containing userid,
  1050.         password, and the accounting field.
  1051.  
  1052.         '''
  1053.         host = host.lower()
  1054.         user = None
  1055.         passwd = None
  1056.         acct = None
  1057.         user = None if host in self._Netrc__hosts else self._Netrc__defuser
  1058.         if not passwd:
  1059.             pass
  1060.         passwd = self._Netrc__defpasswd
  1061.         if not acct:
  1062.             pass
  1063.         acct = self._Netrc__defacct
  1064.         return (user, passwd, acct)
  1065.  
  1066.     
  1067.     def get_macros(self):
  1068.         '''Return a list of all defined macro names.'''
  1069.         return self._Netrc__macros.keys()
  1070.  
  1071.     
  1072.     def get_macro(self, macro):
  1073.         '''Return a sequence of lines which define a named macro.'''
  1074.         return self._Netrc__macros[macro]
  1075.  
  1076.  
  1077.  
  1078. def test():
  1079.     '''Test program.
  1080.     Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
  1081.  
  1082.     -d dir
  1083.     -l list
  1084.     -p password
  1085.     '''
  1086.     if len(sys.argv) < 2:
  1087.         print test.__doc__
  1088.         sys.exit(0)
  1089.     debugging = 0
  1090.     rcfile = None
  1091.     while sys.argv[1] == '-d':
  1092.         debugging = debugging + 1
  1093.         del sys.argv[1]
  1094.     if sys.argv[1][:2] == '-r':
  1095.         rcfile = sys.argv[1][2:]
  1096.         del sys.argv[1]
  1097.     host = sys.argv[1]
  1098.     ftp = FTP(host)
  1099.     ftp.set_debuglevel(debugging)
  1100.     userid = passwd = acct = ''
  1101.     
  1102.     try:
  1103.         netrc = Netrc(rcfile)
  1104.     except IOError:
  1105.         if rcfile is not None:
  1106.             sys.stderr.write('Could not open account file -- using anonymous login.')
  1107.         
  1108.  
  1109.     
  1110.     try:
  1111.         (userid, passwd, acct) = netrc.get_account(host)
  1112.     except KeyError:
  1113.         sys.stderr.write('No account -- using anonymous login.')
  1114.  
  1115.     ftp.login(userid, passwd, acct)
  1116.     for file in sys.argv[2:]:
  1117.         if file[:2] == '-l':
  1118.             ftp.dir(file[2:])
  1119.             continue
  1120.         if file[:2] == '-d':
  1121.             cmd = 'CWD'
  1122.             if file[2:]:
  1123.                 cmd = cmd + ' ' + file[2:]
  1124.             resp = ftp.sendcmd(cmd)
  1125.             continue
  1126.         if file == '-p':
  1127.             ftp.set_pasv(not (ftp.passiveserver))
  1128.             continue
  1129.         ftp.retrbinary('RETR ' + file, sys.stdout.write, 1024)
  1130.     
  1131.     ftp.quit()
  1132.  
  1133. if __name__ == '__main__':
  1134.     test()
  1135.